package com.jlnk.rxjavademo2.presenter;

import com.jlnk.rxjavademo2.client.NetworkHotRetrofitClient;
import com.jlnk.rxjavademo2.entity.NetworkHotEntity;
import com.jlnk.rxjavademo2.service.NetworkHotService;
import com.jlnk.rxjavademo2.view.NetworkHotView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;

public class NetworkHotPresenter {
    private NetworkHotView view;
    private NetworkHotService service;
    private CompositeDisposable disposable;

    public NetworkHotPresenter(NetworkHotView view) {
        this.view = view;
        Retrofit retrofit = NetworkHotRetrofitClient.getInstance();
        service = retrofit.create(NetworkHotService.class);
        disposable = new CompositeDisposable();
    }

    public void loadNetworkHot() {
        view.showLoading();
        disposable.add(service.getNetworkHot("a03adf6e2a457110183fcbe6881ceeb3")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onNetworkHotSuccess, this::onError));
    }

    private void onNetworkHotSuccess(NetworkHotEntity response) {
        view.hideLoading();
        if (response.getErrorCode() == 0 && response.getResult() != null) {
            view.showNetworkHotItem(response.getResult());
        } else {
            view.showError(response.getReason());
        }
    }

    private void onError(Throwable throwable) {
        view.hideLoading();
        view.showError(throwable.getMessage());
    }

    public void unSubscribe() {
        if (disposable != null) {
            disposable.clear();
        }
    }
}